package Constructions;

import java.awt.Color;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;

import Constructions.EnemyConstructions.EnemyConstructionManager;
import Main.SpaceGame;

public class ConstructionManager 
{
	public ArrayList<Construction> constructionList = new ArrayList<Construction>();
	SpaceGame main;
	public EnemyConstructionManager enemyConstructionManager;
	public boolean showingDefenseGrid;
	
	public ConstructionManager(SpaceGame main)
	{
		this.main=main;
		add(new LifeSupport(37, 43, main));
		add(new AsteroidMiner(37, 27, main));
		add(new Door(42, 35, main));
		add(new Door(48, 35, main));
		add(new Door(45, 32, main));
		add(new Door(45, 38, main));
		for(Construction c:constructionList)
		{
			if (c instanceof Door)
				((Door) c).setClosed(false);
		}
		enemyConstructionManager = new EnemyConstructionManager(main);
		showingDefenseGrid = false;
	}
	
	public void draw(Graphics g)
	{
		for (int i = 0;i<main.constructionManager.constructionList.size();i++)
		{
			main.constructionManager.constructionList.get(i).draw(g);
			if(showingDefenseGrid)
			{
				if(constructionList.get(i) instanceof PPS)
				{
					PPS current = (PPS) constructionList.get(i);
					g.setColor(new Color(0,255,0,50));
					g.fillOval(current.getX()*10-current.pixelRadius, current.getY()*10-current.pixelRadius, current.pixelRadius*2, current.pixelRadius*2);
				}
			}
		}
		enemyConstructionManager.draw(g);
	}
	
	public void add(Construction c)
	{
		constructionList.add(c);
		for (int i = c.getX();i<c.getX()+c.getWidth();i++)
		{
			for (int j = c.getY();j<c.getY()+c.getHeight();j++)
			{
				main.world.tiles[i][j].setHasConstruction(true);
			}
		}
	}
	
	public void remove(int x,int y)
	{
		try
		{
			for (Construction c:constructionList)
			{
				if (c.getX() == x && c.getY() == y)
				{
					constructionList.remove(c);
					for (int i = c.getX();i<c.getX()+c.width;i++)
					{
						for (int j = c.getY();j<c.getY()+c.height;j++)
						{
							main.world.tiles[i][j].setHasConstruction(false);
						}
					}
				}
			}
		}
		catch(ConcurrentModificationException e)
		{
			
		}
	}
	
	public void update()
	{
		for(int i = 0;i<constructionList.size();i++)
		{
			constructionList.get(i).update();
			constructionList.get(i).text.clear();
			constructionList.get(i).colors.clear();
			constructionList.get(i).setText();
		}
		enemyConstructionManager.update();
	}
	
	public Construction getConstruction(int x,int y)
	{
		Construction a = null;
		for(Construction c:constructionList)
		{
			if (c.getX() == x && c.getY() == y)
				a=c;
		}
		return a;
	}
	
	public TeleportPad getTeleportPad()
	{
		TeleportPad t = null;
		for(Construction c:constructionList)
		{
			if (c instanceof TeleportPad)
				t = (TeleportPad) c;
		}
			return t;
	}
}
